package org.example.diet_compass.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.diet_compass.domain.Cart;
import org.example.diet_compass.dto.CartItemDto;
import org.example.diet_compass.service.CartService;
import org.example.diet_compass.mapper.CartMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @author 86135
* @description 针对表【cart(存储购物车信息的表)】的数据库操作Service实现
* @createDate 2025-03-16 15:01:09
*/
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart>
    implements CartService{

    @Resource
    private CartMapper cartMapper;


    @Override
    public void insertCartBatchByGoodIdsAndUserId(int userId, List<Map<String, Object>> goodIdsAndCount) {
        cartMapper.insertCartBatchByGoodIdsAndUserId(userId, goodIdsAndCount);
    }

    @Override
    public Cart getCartGoodByUserIdAndGoodId(int userId, String goodId) {
       return cartMapper.getCartGoodByUserIdAndGoodId(userId,goodId);
    }

    @Override
    public void removeByUserIdAndSelected(Integer userId) {
        cartMapper.removeByUserIdAndSelected(userId);
    }

    @Override
    public List<Cart> getGoodsByUserIdAndSelected(Integer userId) {
        return cartMapper.getGoodsByUserIdAndSelected(userId);
    }

    @Override
    public void updateAllGoods(Boolean selected, Integer userId) {
        int i = selected?1:0;
        cartMapper.updateAllGoods(userId,i);
    }

    @Override
    public void updateGood(Integer userId, String goodId, Integer count, Boolean selected) {
        if (count != null) {
            cartMapper.updateCount(userId,goodId,count);
        }
        if (selected != null) {
           int i = selected ?1:0;
            cartMapper.updateSelected(userId, goodId, i);
        }
    }

    @Override
    public void removeByUserIdAndgoodId(Integer userId, String goodId) {
        cartMapper.removeByUserIdAndGoodId(userId, goodId);
    }

    @Override
    public List<CartItemDto> getGoodsByUserId(Integer userId) {

        List<Map<String, Object>> goodsByUserId = cartMapper.getGoodsByUserId(userId);
        ArrayList<CartItemDto> itemDtos = new ArrayList<>();
        goodsByUserId.stream().forEach(row -> {
            String id = (String) row.get("id");
            String name = (String) row.get("name");
            Double price = (Double) row.get("price");
            Integer count = (Integer) row.get("count");
            String picture = (String) row.get("picture");
            Boolean selected = (Boolean) row.get("selected");
            String description = (String) row.get("description");
            itemDtos.add(new CartItemDto(id,name,price,count,picture,selected,description));
        });
        return itemDtos;
    }
}




